let im = {
	ws: undefined,
	token: undefined,
	lastPongTime: undefined,
	receiveCB: undefined,
	timer: undefined,
	init: function(token, receiveCB) {
		return new Promise((resolve, reject) => {
			this.token = token;
			this.receiveCB = receiveCB;

			if ("WebSocket" in window) {
				console.log("您的浏览器支持 WebSocket!");

				// 打开一个 web socket
				this.ws = new WebSocket("wss://pbnz.ibclubs.com/ws");

				this.ws.onopen = () => {
					this.login(token);

					this.lastPongTime = Date.now();
					this.timer = setInterval(() => {
						this.ping();
					}, 10000)
				};

				this.ws.onmessage = (evt) => {
					if (evt.data === "PONG") {
						this.lastPongTime = Date.now();
					} else if (evt.data === "system error!") {
						console.log("系统错误！", new Date(), evt.data);
						// receiveCB(evt.data);
					} else {
						console.log("数据已接收...", new Date(), JSON.parse(evt.data));
						receiveCB(JSON.parse(evt.data));
					}
				};

				this.ws.onclose = () => {
					console.log("连接已关闭..."); // 关闭 websocket
					clearInterval(this.timer);
				};
			} else {
				// 浏览器不支持 WebSocket
				uni.showToast({
					title: '您的浏览器不支持 WebSocket!',
					icon: 'none'
				})
			}
		})
	},

	close() {
		this.ws.close();
	},

	// 发送消息
	sendMessage: function(message) {
		console.log("数据发送中...", message);
		this.ws.send(JSON.stringify(message));
	},

	// 登录
	login: function(token) {
		console.log("login", token);
		this.sendMessage({
			action: "login",
			param: {
				token
			}
		})
	},

	// 发送心跳包
	ping: function() {
		if (Date.now() - this.lastPongTime > 60000) { // 60秒超时
			uni.showToast({
				title: '连接超时，重连中，请稍后...',
				icon: 'none'
			})
			this.init(this.token, this.receiveCB);
		} else {
			console.log("PING...");
			this.ws.send("PING");
		}
	},

	// 发送聊天内容
	message: function(to_user_id, msg_type, content) {
		this.sendMessage({
			"action": "chart",
			"param": {
				to_user_id,
				msg_type,
				content
			}
		})
	}
}

export default im;
